/**
 * ChatWindow 工具函数模块
 * 包含格式化、用户信息获取等通用工具函数
 */

// 工具函数模块 - 部分函数已迁移到其他文件

export interface User {
  id: string
  name: string
  email: string
  snowflake_id?: string
  open_id?: string
  chat_id?: string
  chat_type?: number
  member_count?: number
  lastTime?: number
  sequence?: number
  read_sequence?: number
}

/**
 * 格式化时间戳
 */
export const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
  const diffTime = today.getTime() - messageDate.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    // 今天
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (diffDays === 1) {
    // 昨天
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (diffDays < 7) {
    // 一周内
    return `${diffDays}天前 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
  } else {
    // 更早
    return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
  }
}

/**
 * 获取最后一条消息预览（简化版本，使用 chatStore）
 */
export const getLastMessagePreview = (
  userId: string,
  chatType?: number
): string => {
  // 这个函数需要访问 chatStore，所以保留在 ChatWindow.ts 中
  // 这里提供一个占位实现
  return ''
  // 找到该用户/群组的最新消息
  const userMessages = messages.value.filter(msg => {
    if (chatType === 2) {
      // 群聊：检查 to_user_id 是否匹配
      const normalizedTargetId = userId.replace(/^group_/i, '').trim().toLowerCase()
      const normalizedMsgToId = (msg.to_user_id || '').replace(/^group_/i, '').trim().toLowerCase()
      return normalizedMsgToId === normalizedTargetId
    } else {
      // 单聊：检查 from_user_id 或 to_user_id 是否匹配
      const isFrom = msg.from_user_id === userId || 
                     (msg.from_user_id && userList.value.some(u => (u.open_id || u.id) === msg.from_user_id && (u.open_id || u.id) === userId)) ||
                     (msg.from_user_id && friendList.value.some(u => (u.open_id || u.id) === msg.from_user_id && (u.open_id || u.id) === userId))
      const isTo = msg.to_user_id === userId ||
                   (msg.to_user_id && userList.value.some(u => (u.open_id || u.id) === msg.to_user_id && (u.open_id || u.id) === userId)) ||
                   (msg.to_user_id && friendList.value.some(u => (u.open_id || u.id) === msg.to_user_id && (u.open_id || u.id) === userId))
      return isFrom || isTo
    }
  })

  if (userMessages.length === 0) {
    return ''
  }

  // 按时间戳排序，获取最新消息
  const lastMessage = userMessages.sort((a, b) => {
    const timeA = a.timestamp_ms || a.timestamp || 0
    const timeB = b.timestamp_ms || b.timestamp || 0
    return timeB - timeA
  })[0]

  if (!lastMessage) {
    return ''
  }

  // 根据消息类型返回预览
  if (lastMessage.message_content_type === 2) {
    // 图片消息
    return '[图片]'
  } else if (lastMessage.message_content_type === 3) {
    // 文件消息
    try {
      const extra = lastMessage.extra ? JSON.parse(lastMessage.extra) : {}
      const fileName = extra.file_name || '文件'
      return `[文件] ${fileName}`
    } catch {
      return '[文件]'
    }
  } else if (lastMessage.message_content_type === 4) {
    // 通话邀请
    return '[通话邀请]'
  } else {
    // 文本消息
    let preview = lastMessage.message || ''
    
    // 如果是群聊消息，显示发送者名称
    if (chatType === 2 && lastMessage.from_user_id) {
      const senderId = lastMessage.from_user_id
      const isCurrentUser = currentUserId.value && (senderId === currentUserId.value || 
        userList.value.some(u => (u.open_id || u.id) === senderId && (u.open_id || u.id) === currentUserId.value) ||
        friendList.value.some(u => (u.open_id || u.id) === senderId && (u.open_id || u.id) === currentUserId.value))
      
      if (isCurrentUser) {
        preview = `我: ${preview}`
      } else {
        // 尝试从缓存中获取发送者名称
        const groupId = userId.replace(/^group_/i, '').trim()
        const cacheKey = `${groupId}_${senderId}`
        const cachedInfo = groupMembersCache.value.get(cacheKey)
        const senderName = cachedInfo?.alias || cachedInfo?.displayName || cachedInfo?.name || senderId
        preview = `${senderName}: ${preview}`
      }
    }
    
    // 限制长度
    if (preview.length > 50) {
      preview = preview.substring(0, 50) + '...'
    }
    
    return preview
  }
}

/**
 * 获取最后一条消息时间（简化版本）
 */
export const getLastMessageTime = (
  userId: string,
  chatType?: number
): string => {
  // 这个函数需要访问 chatStore，所以保留在 ChatWindow.ts 中
  // 这里提供一个占位实现
  return ''
  const userMessages = messages.value.filter(msg => {
    if (chatType === 2) {
      const normalizedTargetId = userId.replace(/^group_/i, '').trim().toLowerCase()
      const normalizedMsgToId = (msg.to_user_id || '').replace(/^group_/i, '').trim().toLowerCase()
      return normalizedMsgToId === normalizedTargetId
    } else {
      const isFrom = msg.from_user_id === userId || msg.to_user_id === userId
      return isFrom
    }
  })

  if (userMessages.length === 0) {
    return ''
  }

  const lastMessage = userMessages.sort((a, b) => {
    const timeA = a.timestamp_ms || a.timestamp || 0
    const timeB = b.timestamp_ms || b.timestamp || 0
    return timeB - timeA
  })[0]

  if (!lastMessage) {
    return ''
  }

  const timestamp = lastMessage.timestamp_ms || lastMessage.timestamp || 0
  return formatTime(timestamp)
}

/**
 * 获取用户首字母（用于头像显示）
 * 注意：这个函数需要访问上下文数据，所以实际实现在 ChatWindow.ts 中
 */
export const getUserInitial = (
  userId: string | null
): string => {
  // 占位实现，实际逻辑在 ChatWindow.ts 中
  if (!userId) return 'U'
  return userId[0].toUpperCase()
  if (!userId) return 'U'

  // 检查是否是群组
  if (userId.startsWith('group_') || groupsCache.value.has(userId)) {
    const groupId = normalizeGroupId(userId)
    const groupInfo = groupsCache.value.get(userId) || groupsCache.value.get(`group_${groupId}`)
    if (groupInfo?.group_name) {
      return groupInfo.group_name[0].toUpperCase()
    }
    return 'G'
  }

  // 查找用户
  let user = userList.value.find(u => 
    u.open_id === userId || u.id === userId || (u.snowflake_id && String(u.snowflake_id) === userId)
  )

  if (!user) {
    user = friendList.value.find(u => 
      u.open_id === userId || u.id === userId || (u.snowflake_id && String(u.snowflake_id) === userId)
    )
  }

  if (user && user.name) {
    return user.name[0].toUpperCase()
  }

  return userId[0].toUpperCase()
}

/**
 * 获取用户显示名称
 * 注意：这个函数需要访问上下文数据，所以实际实现在 ChatWindow.ts 中
 */
export const getUserName = (
  userId: string | null
): string => {
  // 占位实现，实际逻辑在 ChatWindow.ts 中
  if (!userId) return 'Unknown'
  return userId
  if (!userId) return 'Unknown'

  // 检查是否是群成员（在群聊中）
  if (currentTargetId.value) {
    const groupId = normalizeGroupId(currentTargetId.value)
    const cacheKey = `${groupId}_${userId}`
    const cachedInfo = groupMembersCache.value.get(cacheKey)
    if (cachedInfo) {
      return cachedInfo.alias || cachedInfo.displayName || cachedInfo.name || userId
    }
  }

  // 查找用户
  let user = userList.value.find(u => 
    u.open_id === userId || u.id === userId || (u.snowflake_id && String(u.snowflake_id) === userId)
  )

  if (!user) {
    user = friendList.value.find(u => 
      u.open_id === userId || u.id === userId || (u.snowflake_id && String(u.snowflake_id) === userId)
    )
  }

  if (user && user.name) {
    return user.name
  }

  return userId
}

/**
 * 标准化群组ID
 */
export const normalizeGroupId = (id: string): string => {
  return id.replace(/^group_/i, '').trim().toLowerCase()
}

